<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import index from '@/components/analysisSheetComponents/ambientAir/tmpl68/index.vue'
import {useAnalysetStore} from "@/store/index.ts";
import AnalyesAPI from "@/api/system/analyes.ts";
import {
  filterParallelSamples,
  filterValidSampleAdatas,
  filterValidSamples, jbylSamples,
  kbylSamples,
  processTableData,splitDataIntoPages, getHeaders,
  qxylSamples, zkylSamples
} from '@/utils/method';
import {transformData} from "@/utils/method";
// 复制粘贴
import Index from '@/components/analysisSheetComponents/component/index.vue';
import Device from "@/components/analysisSheetComponents/component/Device.vue";
import IndexPdf from "@/components/analysisSheetComponents/ambientAir/tmpl68/indexPdf.vue";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "column": 10, // 列数
      "defaultRowHeight": 30, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "类型",}, // B1
        {"r": 0, "c": 2, "v": "稀释倍数K",}, // B1
        {"r": 0, "c": 3, "v": "S甲烷",}, // B1
        {"r": 0, "c": 4, "v": "C甲烷mg/m³",}, // B1
        {"r": 0, "c": 5, "v": "S总烃",}, // B1
        {"r": 0, "c": 6, "v": "C总烃含氧峰mg/m³",}, // B1
        {"r": 0, "c": 7, "v": "C总烃mg/m³",}, // B1
        {"r": 0, "c": 8, "v": "C非甲烷总烃mg/m³",}, // B1
        {"r": 0, "c": 9, "v": "测定结果",}, // B1
        {"r": 0, "c": 10, "v": "备注",}, // B1
        {"r": 1, "c": 7, "v": "",}, // B1

      ], // 初始化数据
      "config": {
        "merge": {
          "1_7": {
            "r": 0, // 起始行
            "c": 7, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
        }, // 合并单元格
        "columnlen": { // 设置列宽
          "0": 130, // 第一列宽度 100%
          "1": 130, // 第二列宽度 120px
          "2": 130, // 第三列宽度 180px
          "3": 130, // 第四列宽度 100px
          "4": 100, // 第五列宽度 200px
          "5": 100,  // 第六列宽度 100%
          "6": 100,  // 第六列宽度 100%
          "7": 100,  // 第六列宽度 100%
          "8": 100,  // 第六列宽度 100%
          "9": 100,  // 第六列宽度 100%
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const waterForm = ref({
  bdatas: {
    checkList: [],
    jwcfmj: {},
    jwcfsj: {},
    jwnd: {},
    ztnd: {},
    ztcfsj: {},
    ztcfmj: {},
    qxjhdcd: [
      {qx_ypbh: '', qx_cdjg: '', qx_xd: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_cdjg: '', qx_xd: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_cdjg: '', qx_xd: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_cdjg: '', qx_xd: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_cdjg: '', qx_xd: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_cdjg: '', qx_xd: '', qx_zkyq: '', qx_sfhg: ''}
    ],
    pxycd_fx: {},
  },
  kbycd: [
    {kb_ypbh: '', kb_kbz: '', kb_zkzb: '', kb_sfhg: '', kb_ypbh1: '', kb_kbz1: '', kb_zkzb1: '', kb_sfhg1: '',},
    {kb_ypbh: '', kb_kbz: '', kb_zkzb: '', kb_sfhg: '', kb_ypbh1: '', kb_kbz1: '', kb_zkzb1: '', kb_sfhg1: '',},
    {kb_ypbh: '', kb_kbz: '', kb_zkzb: '', kb_sfhg: '', kb_ypbh1: '', kb_kbz1: '', kb_zkzb1: '', kb_sfhg1: '',},
    {kb_ypbh: '', kb_kbz: '', kb_zkzb: '', kb_sfhg: '', kb_ypbh1: '', kb_kbz1: '', kb_zkzb1: '', kb_sfhg1: '',},
    {kb_ypbh: '', kb_kbz: '', kb_zkzb: '', kb_sfhg: '', kb_ypbh1: '', kb_kbz1: '', kb_zkzb1: '', kb_sfhg1: '',},
  ],
  pxycd: [],
  bnotes: '',
  unit: {},
  cdtj: {},
  // 复制粘贴
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  }
})
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const processedData = ref([])
const cdatas = ref([])
const checkDialogVisible = ref(false)
const checkTime = ref('')
const switchAB = ref(true)
const sheetData = ref('')
const jsonData = ref(null)
const switchAdd = ref(true)
const listB = ref({
  kbyList: [],
  qxyList: [],
  pxyList: [],
  bzyList: [],
})
const showTargetPage = ref(false)
const tableHeaders = ref([])
const tabler = ref([])

// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  sheetData.value = options.data
  // 获取表单信息
  getWaterCapacity()
  // 复制粘贴
  getMethod()
});


// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates
}
// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 25,
    record_sn: record_sn,
    // record_sn: 40,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    console.log('获取水质容量 A单', data)
    // 复制粘贴
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data
      waterForm.value.bdatas = Array.isArray(data.bdatas) && data.bdatas.length === 0 ? {} : data.bdatas;
      waterForm.value.unit = Array.isArray(data.unit) && data.unit.length === 0 ? {} : data.unit;
      sheetData.value = data.configs
      options.data = sheetData.value
      luckysheet.create(options);
      processedData.value = data.adatas
      //处理adata到pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 20)
      console.log(tableHeaders.value)
      tabler.value = getHeaders(data.adatas, 7)
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      }
    }
  })
}

//加载本地数据
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  // 调用函数
  processedData.value = filterValidSampleAdatas(processTableData(data));
  cdatas.value = filterValidSamples(transformData(processedData.value))
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status
    delete waterForm.value.reviewer_id
  }
//   调接口拿数据
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 68,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
};

const handleSwitch = () => {
  switchAB.value = !switchAB.value
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  listB.value.kbyList = kbylSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.qxyList = qxylSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.pxyList = filterParallelSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.bzyList = zkylSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.jbyList = jbylSamples(filterValidSampleAdatas(processTableData(data)));
  console.log(listB.value)
}
// 下载
const downloadDetail = async () => {
  showTargetPage.value = true
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false
  }, 1000);
};
</script>

<template>
  <div class="card">
    <div v-show="switchAB && !showTargetPage">
      <el-card class="box-card">
        <h1 style="text-align: center">环境空气和废气 总烃/甲烷/非甲烷总烃分析原始记录（A面）</h1>
        <div>SXLPHJ/JL/CX-22-68</div>
        <table class="table">
          <tr style="background-color: #f2f2f2">
            <td colspan="2">任务编号</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.task_name" />
            </td>
            <td>采样日期</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.sampling_time" />
            </td>
            <td colspan="1">分析日期</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.anal_time" />
            </td>
          </tr>
          <tr>
            <td colspan="2">分析方法</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.method" />
            </td>
            <td colspan="1">检出限</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.limit_val" />
            </td>
          </tr>
          <Device :water-form="waterForm" :colspan="4"></Device>
          <tr>
            <td colspan="2">环境温度</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.temperature">
                <template #append>
                  <span style="background-color: transparent;color: black">℃</span>
                </template>
              </el-input>
            </td>
            <td>环境湿度</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.humidity">
                <template #append>
                  <span style="background-color: transparent;color: black">%RH</span>
                </template>
              </el-input>

            </td>
            <td colspan="1">样品类别</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.category_id" />
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td colspan="2">测定条件</td>
            <td colspan="10">
              <div style="display: flex;align-items: center;">
                测定条件：
                <el-input style="border: 1px solid transparent" placeholder="请输入" v-model="waterForm.cdtj.cdtj1" />
                进样量：
                <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                  v-model="waterForm.cdtj.cdtj2" />
              </div>

            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 100px;">计算公式</td>
            <td colspan="10">
              <el-input style="width: 200px;border: 1px solid transparent" placeholder="请输入"
                v-model="waterForm.js_formula" />
            </td>
          </tr>
        </table>
        <div id="luckysheet" style="width:100%;height:500px;"></div>
        <table class="table">
          <tr style="text-align: center;">
            <td style="width: 5%;">备注</td>
            <td colspan="10">
              <el-checkbox-group v-model="waterForm.bdatas.checkList">
                <el-checkbox label="甲烷" value="甲烷" />
                <el-checkbox label="以甲烷计" value="以甲烷计" />
                <el-checkbox label="以碳计" value="以碳计" />
                <el-checkbox label="总烃" value="总烃" />
                <el-checkbox label="以甲烷计" value="以甲烷计" />
                <el-checkbox label="以碳计" value="以碳计" />
                <el-checkbox label="非甲烷总烃" value="非甲烷总烃" />
                <el-checkbox label="以甲烷计" value="以甲烷计" />
                <el-checkbox label="以碳计" value="以碳计" />
              </el-checkbox-group>
            </td>
          </tr>
        </table>
      </el-card>
    </div>
    <div v-show="!switchAB && !showTargetPage">
      <index :waterForm="waterForm" :list-b="listB"></index>
    </div>
    <!--    提交校核-->
    <!--    底部公共按钮-->
    <div v-show="showTargetPage">
      <IndexPdf :water-form="waterForm" :tableHeaders="tableHeaders" :tabler="tabler"></IndexPdf>
    </div>

    <!--    底部公共按钮-->
    <div v-show="!showTargetPage">
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh" :handle-switch="handleSwitch"
        :get-water-capacity="getWaterCapacity" :switch-add="switchAdd" :switch-a-b="switchAB"
        :download-detail="downloadDetail" :switch="true"></Index>
    </div>

  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
